﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Configuration;
using IReaper.Configurations;
using System.Threading;
using IReaper.Properties;

namespace IReaper
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //application default
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //try to open an exitsing event
            if (HaveOtherInstance())
            { return; }
            //初始化一些全局参数
            GlobalInit();
            Initializer.WelcomePanel welcome = new Initializer.WelcomePanel();
            if (welcome.ShowDialog() != DialogResult.Cancel)
            {
                Application.Run(new MainForm());
            }
        }

        /// <summary>
        /// 检测是否已经有实例启动
        /// </summary>
        /// <returns></returns>
        private static bool HaveOtherInstance()
        {
            try
            {
                EventWaitHandle globalHandler = EventWaitHandle.OpenExisting("iReaper");
                globalHandler.Set();
                return true;
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                EventWaitHandle global = new EventWaitHandle(true, EventResetMode.AutoReset, "iReaper");
                Thread monitor = new Thread(new ThreadStart(delegate()
                {
                    while (true)
                    {
                        global.WaitOne();
                        Form form = Core.CoreData[CoreDataType.ApplicationForm] as Form;
                        if (form != null)
                        {
                            form.BeginInvoke(new ThreadStart(form.Show));
                        }
                    }
                }));
                monitor.IsBackground = true;
                monitor.Start();
                GC.KeepAlive(monitor);
                return false;
            }
        }

        private static void GlobalInit()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            //init browser
            IReaper.CommonGui.ButtonStatuMonitor.Init();
            //check for upgrade
            if (Properties.Settings.Default.CallUpgrade)
            {
                Settings.Default.Upgrade();
                Settings.Default.CallUpgrade = false;
                Settings.Default.Save();
            }
            //create runningCourseFile
            Core.CoreData[CoreDataType.CurrentViewedFiles] = new FileData.RunningCourseFileDataCollection(true);
            //ToolStripManager.Renderer = new iReaperToolStripRender();
            IReaper.Utils.SetCulture(Application.CurrentCulture);
        }
    }
}